#!/bin/bash

# 此脚本需要在tomcat节点执行，包括检测进程状态、端口状态、内存占用

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
# 告警缓存文件
alarm_file_tmp="tmp/tomcat_check_alarm.txt"
echo -n "" >${alarm_file_tmp}
# 本机ip
local_ip=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")
# tomcat端口
tomcat_port=$(cat config.cnf | grep TomcatPort | awk -F "=" '{print $2}')
# tomcat内存占用阈值
tomcat_mem_threshold=$(cat config.cnf | grep TomcatMemThreshold | awk -F "=" '{print $2}')
execute_cycle=$(cat config.cnf | grep ExecuteCycle | awk -F "=" '{print $2}')


# tomcat运行状态监控
tomcat_status_check() {
    tomcat_status=$(ps -elf | grep tomcat | grep -v grep  | grep -v cmptomcat | grep -v tomcat_check | wc -l)
    # 检查状态是否为 active
    if [[ ${tomcat_status} -lt 1 ]]; then
        # 非active状态进行告警
         ./gen_alarm.sh -g "应用进程监控" "tomcat服务运行状态异常,tomcat进程不存在,IP:$(hostname -I)" 3 "tomcat状态" "tomcat_status" ${alarm_file_tmp}
    else
        # 状态正常且存在状态告警，则需要恢复告警
        ./gen_alarm.sh -r "应用进程监控" "tomcat运行状态恢复正常,IP:$(hostname -I)" "tomcat状态" "tomcat_status" ${alarm_file_tmp}

        # 端口检查
        tomcat_port_check
        # 内存占用检查
        #tomcat_mem_check
    fi
}

# tomcat运行端口监控
tomcat_port_check() {
    port=$(netstat -nplt | grep ":${tomcat_port} ")
    if [[ ${port} == '' ]]; then
        # 端口未监听，告警
         ./gen_alarm.sh -g "端口状态" "tomcat服务端口[${tomcat_port}]未监听,IP:$(hostname -I)" 3 "tomcat端口状态" "tomcat_port" ${alarm_file_tmp}
    else
        # 端口正常且存在告警，需要恢复告警
        ./gen_alarm.sh -r "端口状态" "tomcat服务端口[${tomcat_port}]恢复正常,IP:$(hostname -I)" "tomcat端口状态" "tomcat_port" ${alarm_file_tmp}
    fi
}

# 内存占用
tomcat_mem_check() {
    tomcat_pid=$(ps -ef | grep tomcat | grep java | awk 'NR==1 {print $2}')
    tomcat_mem=$(cat /proc/${tomcat_pid}/status | grep -e VmRSS | awk 'NR==1 {print $2}')
    if [[ ${tomcat_mem} -gt ${tomcat_mem_threshold} ]]; then
        # 内存告警
         ./gen_alarm.sh -g "Java堆内存" "tomcat内存占用超出阈值${tomcat_mem_threshold}KB,当前占用内存${tomcat_mem}KB,IP:$(hostname -I)" 2 "tomcat内存占用" "tomcat_mem" ${alarm_file_tmp}
    else
        # 内存告警恢复
        ./gen_alarm.sh -r "Java堆内存" "tomcat内存占用恢复正常，阈值${tomcat_mem_threshold}KB,当前占用内存${tomcat_mem}KB,IP:$(hostname -I)" "tomcat内存占用" "tomcat_mem" ${alarm_file_tmp}
    fi
}

while true; do
    holidays_date=$(cat config.cnf | grep Holidays | awk -F "=" '{print $2}' | sed "s/,/ /g")
	current_date=$(date +'%Y-%m-%d')
	echo $holidays_date | grep -o $current_date >> /dev/null
	if [[ $? -eq 0 ]]; then
		exit 0
	else
		echo -n "" >${alarm_file_tmp}
		tomcat_status_check
		# 将缓存告警放入告警文件夹
		./gen_alarm.sh -s ${alarm_file_tmp}
		sleep ${execute_cycle}
	fi
done